<template>
	<view class="order_container">
		<!-- 订单状态栏 -->
		<view class="status_tab" >
			<view class="state_item" 
				v-for="(item, index) of tabData" 
				:key="index"
				:class="{'selectedIndex': activeIndex == item.value}"
				@click="changeState(item.value)"
				>
				{{ item.text }}
			</view>
		</view>
		<!-- 订单为空提示 -->
		<view class="empty_tip" v-if="emptyOrderFlag">
			暂无该状态订单
		</view>
		<!-- 订单列表 -->
		<view class="order_list">
			<view class="order_item" 
				v-for="(item, index) of showOrderData" 
				:key="index"
				:class="{'margintop_not_firstitem': index != 0}"
				>
				<!-- 订单状态 -->
				<view class="order_state_box">
					<view class="order_state_box_tip">
						订单状态
					</view>
					<view class="order_state_box_value">
						{{ item.statusText }}
					</view>
				</view>
				<view class="order_info" >
					<view class="order_info_pic" @click="gotoGoodsDetail(item)">
						<image :src="baseUrl + item.goods.cover" 
							mode="widthFix"
							class="order_godds_pic"
							></image>
					</view>
					<view class="order_info_base" @click="gotoOrderDetail(item)">
						<!-- 商品名和价格 -->
						<view class="order_info_name_price">
							<view class="order_info_name">
								{{ item.goods.goods_name }}
							</view>
							<view class="order_info_price">
								￥<span style="font-size: 17px;">{{ item.goods.price }}</span>
							</view>
						</view>
						<!-- 规格和数量 -->
						<view class="order_info_speci_num">
							<view class="order_info_specis">
								<view class="order_info_speci_item" 
									v-for="(item1, index1) of item.orderSpecifications" 
									:key="index1"
									v-if="item.orderSpecifications.length != 0"
									>
									{{ item1.speci_value }}
								</view>
							</view>
							<view class="order_info_num">
								x {{ item.number }}
							</view>
						</view>
					</view>
				</view>
				<view class="order_ops">
					<view class="order_real_price">
						实付:<span style="color: red;">
								￥<span style="font-size: 15px;">{{ item.real_price }}</span>
							</span>
					</view>
					<!-- 各状态按钮组 -->
					<!-- 待支付按钮组 -->
					<view class="order_ops_btns" v-if="item.order_status == 0">
						<view class="goto_pay">
							<button type="default" 
								class="goto_pay_btn" 
								@click="gotoPay(item)"
								>去付款</button>
						</view>
					</view>
					<!-- 待发货按钮组 -->
					<view class="order_ops_btns" v-if="item.order_status == 1">
						<view class="urge_send">
							<button type="default" class="urge_send_btn" @click="urgeHanle">催发货</button>
						</view>
					</view>
					<!-- 待收货按钮组 -->
					<view class="order_ops_btns" v-if="item.order_status == 2">
						<view class="check_logistics">
							<button type="default" class="check_logistics_btn" @click="CheckLogistics">查看物流</button>
						</view>
					</view>
					<!-- 售后按钮组 -->
					<view class="order_ops_btns" v-if="item.order_status == 3">
						<view class="contact_service">
							<button type="default" class="contact_service_btn">联系客服</button>
						</view>
						<view class="check_after_sale">
							<button type="default" class="check_after_sale_btn">查看售后</button>
						</view>
					</view>
					<!-- 完成按钮组 -->
					<view class="order_ops_btns" v-if="item.order_status == 4">
						<view class="delete_order">
							<button type="default" class="delete_order_btn" @click="deleteOrderHandle(item.orderId)">删除订单</button>
						</view>
						<view class="evaluate">
							<button type="default" class="evaluate_btn">评价</button>
						</view>
					</view>
					<!-- 已取消按钮组 -->
					<view class="order_ops_btns" v-if="item.order_status == 5">
						<view class="delete_order">
							<button type="default" class="delete_order_btn" @click="deleteOrderHandle(item.orderId)">删除订单</button>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from "vue"
import { onLoad, onShow } from "@dcloudio/uni-app"

// 当前激活的状态索引
let activeIndex = ref(100);
// 订单数据
let orderData = ref([]);
// 激活状态的订单数据(展示的数据)
let showOrderData = ref([]);
// 图片基础路径
let baseUrl = uni.$baseUrl
// 订单数据为空标识
let emptyOrderFlag = ref(false);

// 状态栏静态数据
let tabData = [
	{text: "全部", value: 100},
	{text: "待付款", value: 0},
	{text: "待发货", value: 1},
	{text: "待收货", value: 2},
	{text: "售后", value: 3},
	{text: "已完成", value: 4},
	{text: "已取消", value: 5},
]

// 获取页面跳转时传入的默认激活状态值
onLoad((options)=>{
	activeIndex.value = options.state;
})

onMounted(()=>{
	getOrderData();
})

onShow(()=>{
	getOrderData();
	// uni.$checkLogin();
})

// 去付款
function gotoPay(item){
	
	// console.log("去付款====>", item);
	
	// 检查订单还在不在支付有效期
	const orderDate = new Date(item.create_time);
	const endDate = new Date(orderDate.getTime() + 15 * 60 * 1000); // 获取支付过期时间戳
	const now = new Date(); // 获取当前时间戳
	const difference = Math.floor((endDate - now) / 1000); // 计算剩余时间差（秒）
	
	if(difference <= 0){
		uni.showToast({
			title: '订单支付超时，已取消',
			icon: "none"
		});
		return 1;
	}
	
	// console.log("订单有效，剩余支付时间：", difference);
	
	// 取出订单ID，传到付款页面
	let orderId = item.order_id;
	
	// 更改本地存储中的OrderInfo
	let orderInfo = {
		goodsInfo: item.goods,
		address: item.address,
		specifications: item.orderSpecifications, // 选择的商品规格
		number: item.number
	}
	
	uni.setStorageSync("orderInfo", JSON.stringify(orderInfo));
	
	// 携带参数，页面跳转
	uni.navigateTo({
		url:`/subPkg2/pay/pay?orderId=${orderId}`
	})
}

// 获取当前用户的所有订单数据
async function getOrderData(){
	// 获取当前登录用户ID
	let userInfo = uni.getStorageSync("userInfo");
	
	// 发送请求获取订单数据
	const res = await uni.$http.get(`/order/list/${userInfo.user_id}`);
	orderData.value = res.data.data;
	
	// console.log("获取的订单列表===>", res.data.data);
	
	// 过滤展示数据
	filterOrderData();
}

// 变更选中订单状态.重新过滤不同状态的订单数据展示
function changeState(newIndex){
	activeIndex.value = newIndex;
	
	filterOrderData();
}

// 过滤出需要展示的订单数据
function filterOrderData(){
	// 判断是否需要过滤, 如果激活的索引是100则显示全部
	if(activeIndex.value == 100){
		emptyOrderFlag.value = false; // 标识不为空
		showOrderData.value = orderData.value;
		return 1;
	}
	
	// 根据当前激活的索引, 过滤出需要展示的订单数据
	for(let item of orderData.value){
		showOrderData.value = orderData.value.filter((item)=>{
			// 动态添加字段orderStatusText，显示订单状态文本
			let statusText = coverOrderStatus(item.order_status);
			item["statusText"] = statusText;
			return item.order_status == activeIndex.value;
		})
	}
	
	// console.log("展示的数据:", showOrderData.value);
	
	// 检查当前状态显示的商品数是否为0（为空判断）
	if(showOrderData.value.length == 0){
		emptyOrderFlag.value = true;
	}else{
		emptyOrderFlag.value = false;
	}
	
}

// 跳转商品详情页面
function gotoGoodsDetail(item){
	// 将商品信息设置上
	uni.setStorageSync("goodsDetail", JSON.stringify(item.goods));
	// 页面跳转
	uni.navigateTo({
		url: "/subPkg1/goods_detail/goods_detail"
	})
}

// 跳转到订单详情页面
function gotoOrderDetail(item){
	uni.setStorageSync("view_order", item);
	
	uni.navigateTo({
		url: "/subPkg2/view_order/view_order"
	})
	
}

// 根据传入的订单状态返回订单需要显示的文本
function coverOrderStatus(statusN){
	let statusText = ""; // 返回的文本
	switch(statusN){
		case 0:
			statusText = "待付款"
			break;
		case 1:
			statusText = "待发货"
			break;
		case 2:
			statusText = "待收货"
			break;
		case 3:
			statusText = "售后处理"
			break;
		case 4:
			statusText = "交易完成"
			break;
		case 5:
			statusText = "订单取消"
			break;
	}
	return statusText;
}

// 模拟催促
function urgeHanle(){
	uni.showLoading({
		title: '短信通知...',
		mask: true
	});
	
	setTimeout(()=>{
		uni.showToast({
			title:"已帮忙催促",
			duration: 2000,
			image: baseUrl + "cat/angry.gif"
		});
	}, 1000)
}

// 查看物流处理器
function CheckLogistics(){
	uni.showToast({
		duration: 2000,
		image: baseUrl + "cat/eat_melon.gif"
	});
}

// 删除订单处理器
function deleteOrderHandle(orderId){
	// 确定删除提示
	uni.showModal({
		title: '提示',
		content: '确定删除？',
		success: function (res) {
			if (res.confirm) {
				uni.showToast({
					title:"就不给你删",
					duration: 2000,
					image: baseUrl + "cat/delete_not.gif"
				});
				// execDelete(orderId)
			} else if (res.cancel) {
				uni.showToast({
					title: '取消删除',
					icon: "none"
				});
			}
		}
	});
	
}

// 删除执行器
async function execDelete(orderId){
	const res = await uni.$http.delete(`/orderInfos/deleteOrder/${orderId}`);
	
	if(res.data.code == 1){
		uni.showToast({
			title: '删除成功',
			icon: "none"
		});
		activeIndex.value = 100;
		getOrderData();
		return 1;
	}
	
	uni.showToast({
		title: '删除失败!',
		icon: "none"
	});
	
}

</script>

<style lang="scss" scoped>
.status_tab{
	width: 100vw;
	display: flex;
	// border: solid red 1px;
	white-space: nowrap;
	overflow-x: auto;
}

.state_item{
	padding: 20rpx 30rpx;
	// border: solid #fffa4f 1px;
}

.selectedIndex{
	font-weight: 600;
	font-size: 18px;
}

.order_list{
	margin-top: 10rpx;
	
}

.order_item{
	background-color: #fff;
	// border: solid #89ff91 1px;
	padding: 30rpx 15px;
}

.order_info{
	display: flex;
	padding: 30rpx 0px 5rpx 0px;
}

.order_info_pic{
	width: 20%;
	position: relative;
}

.order_godds_pic{
	width: 100%;
}

.margintop_not_firstitem{
	margin-top: 15rpx;
}

.order_info_base{
	width: 80%;
	position: relative;
}

.order_info_name{
	width: 75%;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.order_info_price{
	color: red;
	font-size: 15px;
}

.order_info_name_price{
	display: flex;
	justify-content: space-between;
	padding: 0px 10rpx;
}

.order_info_name{
	font-weight: 600;
}

.order_info_speci_num{
	display: flex;
	justify-content: space-between;
	padding: 20rpx 10rpx;
	
}

.order_info_num{
	color: #4c4c4c;
	font-size: 14px;
}

.empty_tip{
	font-size: 14px;
	color: #4f4f4f;
	padding: 15rpx 0px;
	text-align: center;
}

.order_state_box{
	display: flex;
	justify-content: space-between;
	border-bottom: solid #d1d1d1 1px;
	padding-bottom: 10rpx;
	font-size: 14px;
}

.order_state_box_value{
	color: red;
}

.order_ops{
	display: flex;
	justify-content: space-between;
	align-items: center;
	// border: solid red 1px;
}

.order_ops_btns button{
	height: 60rpx;
	font-size: 13px;
}

.order_real_price{
	font-size: 13px;
}

.urge_send_btn{
	background-color: #f1a03d;
	color: #fff;
}

.goto_pay_btn{
	background-color: #8fdd8b;
	color: #fff;
}

.check_logistics_btn{
	background-color: #54d3e6;
	color: #fff;
}

.contact_service_btn{
	background-color: #5885e6;
	color: #fff;
}

.check_after_sale_btn{
	background-color: #e6a591;
	color: #fff;
}

.delete_order_btn{
	background-color: #e53134;
	color: #fff;
}

.evaluate_btn{
	background-color: #ffaa7f;
	color: #fff;
}
</style>
